package com.szgz.platform.controller;

import com.szgz.platform.service.CodeRunService;
import com.szgz.platform.service.ContainerOrchestrationService;
import com.szgz.platform.service.ResourceSchedulerService;
import com.szgz.platform.result.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class RunCodeController {

    @Autowired
    private CodeRunService codeRunService;

    @Autowired
    private ContainerOrchestrationService containerOrchestrationService;

    @Autowired
    private ResourceSchedulerService resourceSchedulerService;

    @PostMapping("/run")
    public ApiResponse<String> runCode(@RequestBody RunCodeRequest request) {
        String output = codeRunService.runCode(request.getCode(), request.getLanguage());
        return ApiResponse.success(output);
    }

    @PostMapping("/run/advanced")
    public ApiResponse<Map<String, Object>> runCodeAdvanced(@RequestBody RunCodeRequest request) {
        Map<String, Object> payload = new HashMap<>();
        
        try {
            // 请求资源分配
            ResourceSchedulerService.ResourceRequest resourceRequest = 
                new ResourceSchedulerService.ResourceRequest(
                    request.getUserId(), 
                    request.getLanguage(), 
                    5, // 默认优先级
                    512 * 1024 * 1024L, // 512MB内存
                    1L // 1个CPU核心
                );
            
            ResourceSchedulerService.ResourceAllocation allocation = 
                resourceSchedulerService.requestResource(resourceRequest);
            
            if (allocation.isAllocated()) {
                // 使用新的容器编排服务运行代码
                ContainerOrchestrationService.CodeExecutionResult result = 
                    containerOrchestrationService.runCode(request.getCode(), request.getLanguage(), request.getUserId(), request.getStdin());
                
                payload.put("success", result.isSuccess());
                payload.put("output", result.getOutput());
                payload.put("error", result.getError());
                payload.put("containerId", allocation.getContainerId());
                
                // 释放资源
                resourceSchedulerService.releaseResource(allocation.getContainerId());
            } else {
                payload.put("success", false);
                payload.put("error", allocation.getMessage());
                payload.put("waitTime", allocation.getWaitTime());
            }
            
        } catch (Exception e) {
            payload.put("success", false);
            payload.put("error", "执行失败: " + e.getMessage());
            return ApiResponse.fail("执行失败: " + e.getMessage());
        }
        
        return ApiResponse.success(payload);
    }

    @GetMapping("/languages")
    public ApiResponse<List<String>> getSupportedLanguages() {
        return ApiResponse.success(containerOrchestrationService.getSupportedLanguages());
    }

    @GetMapping("/stats")
    public ApiResponse<Map<String, Object>> getResourceStats() {
        return ApiResponse.success(resourceSchedulerService.getResourceStats());
    }

    public static class RunCodeRequest {
        private String code;
        private String language;
        private String userId;
        private String stdin;

        public String getCode() { return code; }
        public void setCode(String code) { this.code = code; }
        public String getLanguage() { return language; }
        public void setLanguage(String language) { this.language = language; }
        public String getUserId() { return userId; }
        public void setUserId(String userId) { this.userId = userId; }
        public String getStdin() { return stdin; }
        public void setStdin(String stdin) { this.stdin = stdin; }
    }
}